package com.unis.common.handler;

import org.apache.shiro.web.servlet.ShiroHttpServletResponse;
import org.atmosphere.cpr.AtmosphereResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by Administrator on 2019/1/8/008.
 */
public class ExceptionResolver extends SimpleMappingExceptionResolver {


    private static final Logger LOG = LoggerFactory.getLogger(ExceptionResolver.class);

    @Override
    protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
                                              Exception ex) {
        String exName = ex.getClass().getSimpleName();
        //ex.printStackTrace();
        LOG.error(ex.getMessage(),ex);
        if ("ClientAbortException".equals(exName)) {
            LOG.warn("ClientAbortException: " + request.getRequestURI());
            if (response instanceof ShiroHttpServletResponse) {
                if (response.isCommitted()) {
                    try {
                        response.getOutputStream().flush();
                        response.getOutputStream().close();
                    } catch (IOException e) {
                    }
                }
            }

            if (response instanceof AtmosphereResponse) {
                if (response.isCommitted()) {
                    try {
                        ((AtmosphereResponse) response).flushBuffer();
                        ((AtmosphereResponse) response).close();
                    } catch (IOException e) {
                        ((AtmosphereResponse) response).closeStreamOrWriter();
                    }
                }
            }
            return null;
        } else {
            return super.doResolveException(request, response, handler, ex);
        }
    }


}
